/*------------------------------------------------------------------------------
 * @file    DELAY.C
 * @author  嵌入式王子
 * @email   donminedm@163.com
 * @date    2024/07/26 21:30:25
 * @brief   开源的嵌入式软件包，本人不对此代码负责任
 * -----------------------------------------------------------------------------*/

#include "delay.h"

static uint32_t fac_us = 0U;

void delay_init(uint32_t SYSCLK)
{
    HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
    fac_us = SYSCLK;
}

void delay_us(uint32_t nus)
{
    uint32_t ticks;
    uint32_t told, tnow, tcnt = 0;
    uint32_t reload = SysTick->LOAD;
    ticks = nus * fac_us;
    told = SysTick->VAL;
    while (1)
    {
        tnow = SysTick->VAL;
        if (tnow != told)
        {
            if (tnow < told)
                tcnt += told - tnow;
            else
                tcnt += reload - tnow + told;
            told = tnow;
            if (tcnt >= ticks)
                break;
        }
    };
}